#!/usr/bin/perl
##########################################################################################################################
##### a script to migrate to viewtopic structure
##########################################################################################################################

##########################################################################################################################
######  TODO list  #######################################################################################################
##########################################################################################################################
##########################################################################################################################

##########################################################################################################################
###### Bug list
##########################################################################################################################
##########################################################################################################################

##########################################################################################################################
# Includes
##########################################################################################################################

use lib qw(../cgi-bin);
use Time::Local qw(timelocal);
use CGI;
use Carp;

use WiganRL;
use Diva::DB;
use Diva::DataObject;
use WiganRL::DataObject;
use WiganRL::DataObject::View;
use WiganRL::DataObject::Viewtopic;
use WiganRL::Search;

use Getopt::Long;
use File::Glob;
use File::Basename;

#use strict;
#use warnings;

$|++;  #unbuffered

##########################################################################################################################
# get arguments
##########################################################################################################################

##########################################################################################################################
# site setup and location variable declarations
##########################################################################################################################
my $cfg= WiganRL::DataObject->load_config('../cgi-bin/wiganrl.ini');

my $cgi= CGI->new();

my $dbh= Diva::DB->new();
$dbh->set( {
	DATABASE_NAME       => $cfg->val('database', 'DATABASE_NAME'),
	DATABASE_SERVER     => $cfg->val('database', 'DATABASE_SERVER'),
	DATABASE_USERNAME   => $cfg->val('database', 'DATABASE_USERNAME'),
	DATABASE_PASSWORD   => $cfg->val('database', 'DATABASE_PASSWORD'),
	DATABASE_TYPE       => $cfg->val('database', 'DATABASE_TYPE'),
	} );
$dbh->connect();
$dbh->debug(0);
WiganRL::DataObject->dbh($dbh);
WiganRL::Search->dbh($dbh);
WiganRL::DataObject->init_class('WWCOM');  #loads contenttypes
WiganRL::DataObject->cgi($cgi);


my ($sth,$rv)= $dbh->get(['VIEW_THREAD'],['*']);
while (my $res= $sth->fetchrow_hashref) {
	$cgi->param('FK_HEADPOST_ID',$res->{'VT_HEADPOST_ID'});
	$cgi->param('FK_LASTPOST_ID',$res->{'VT_LASTPOST_ID'});
	my $v= WiganRL::DataObject::View->new($res->{'VT_HEADPOST_ID'});
	my $l= WiganRL::DataObject::View->new($res->{'VT_LASTPOST_ID'});
	$cgi->param('FK_VIEWFORUM_ID',$v->param('FK_VIEWFORUM_ID'));
	if ($v->param('VIEW_STICKY') eq 'True') {
		$cgi->param('VIEWTOPIC_TYPE','Sticky');
	} else {
		$cgi->param('VIEWTOPIC_TYPE','Normal');
	}
	if ($v->param('VIEW_BLOCKED') eq 'True') {
		$cgi->param('VIEWTOPIC_LOCKED','True');
	} else {
		$cgi->param('VIEWTOPIC_LOCKED','False');
	}
	$cgi->param('VIEWTOPIC_NREPLIES',$res->{'VT_NREPLIES'});
	my $o= WiganRL::DataObject::Viewtopic->new;
	$cgi->param('OBJECT_DATE',$v->param('OBJECT_DATE'));
	$cgi->param('OBJECT_MODIFIED_DATE',$l->param('OBJECT_DATE'));
	$cgi->param('FK_USER_ID',$v->owner->id);
	$cgi->param('OBJECT_NVIEWS',$res->{'VT_NVIEWS'});
	$o->update;

	my $hid= $v->id;
	if ($v->param('FK_HEAD_ID')) {
		$hid= $v->param('FK_HEAD_ID');
	}
	my ($sth2,$rv2)= $dbh->get(['VIEW','OBJECT'],['PK_OBJECT_ID'],'','FK_OBJECT_ID=PK_OBJECT_ID and FK_HEAD_ID='.$hid);
	while (my $res2= $sth2->fetchrow_arrayref) {
		$dbh->update('VIEW',['FK_VIEWTOPIC_ID'],[$o->id],"FK_OBJECT_ID=$res2->[0]");
	}
	$sth2->finish;

#	#update the viewtopic again - it gets this information directly from the view table now
#	$cgi->delete('FK_HEADPOST_ID','FK_LASTPOST_ID','VIEWTOPIC_NREPLIES');
#	$o->update;
	
	print "headpost: ".$v->id.", headid: ".$v->param('FK_HEAD_ID').", vt: ".$o->id."\n";
}
$sth->finish;

#now update the related tables 
my $viewtopic_type= 53;
my $view_type= 3;
my ($sth,$rv)= $dbh->get(['VIEW'],['FK_OBJECT_ID','FK_VIEWTOPIC_ID']);
while (my $res= $sth->fetchrow_arrayref) {
	print "Processing: $res->[0]\n";
	my ($sthr,$rvr)= $dbh->get(['RELATED'],['FK_RELATED_ID','FK_CONTENTTYPE_ID','RELATED_TYPE'],'','FK_OBJECT_ID='.$res->[0]);
	my %related;
	while (my $resr= $sthr->fetchrow_arrayref) {
		$related{$resr->[0]}->{'FK_CONTENTTYPE_ID'}= $resr->[1];
		$related{$resr->[0]}->{'RELATED_TYPE'}= $resr->[2];
		$dbh->dbdelete('RELATED',"FK_RELATED_ID=".$res->[0]." and FK_OBJECT_ID=".$resr->[0]);                
	}
	$dbh->dbdelete('RELATED',"FK_OBJECT_ID=".$res->[0]);
	$sthr->finish;

	for (keys %related) {
		print "Related: $res->[0],$_,$res->[1]\n";
		if ($res->[1]) {
			my ($rv)= $dbh->replace('RELATED',['FK_OBJECT_ID','FK_RELATED_ID','FK_CONTENTTYPE_ID','RELATED_TYPE'],
				[[$res->[1],$_,$related{$_}->{'FK_CONTENTTYPE_ID'},$related{$_}->{'RELATED_TYPE'}]]);
			($rv)= $dbh->replace('RELATED',['FK_OBJECT_ID','FK_RELATED_ID','FK_CONTENTTYPE_ID','RELATED_TYPE'],
				[[$_,$res->[1],$viewtopic_type,$related{$_}->{'RELATED_TYPE'}]]);
		}
	}

	#update head relationships
	($sthr,$rvr)= $dbh->get(['OBJECT'],['FK_HEAD_ID'],'','PK_OBJECT_ID='.$res->[0]);
	if ($rvr>0) {
		#todo - you've got to get the content type of the head , not of the obj
		my $resr= $sthr->fetchrow_arrayref;
		#get the head and itstype
		my ($sthh,$rvh)= $dbh->get(['OBJECT'],['FK_CONTENTTYPE_ID'],'','PK_OBJECT_ID='.$resr->[0]);
		my $resh= $sthh->fetchrow_arrayref;
		$sthh->finish;
		if ($res->[1] and $rvh>0 and $resh->[0] != $view_type) {
			print "Head: $res->[0],$resh->[0]\n";
			my ($rv)= $dbh->replace('RELATED',['FK_OBJECT_ID','FK_RELATED_ID','FK_CONTENTTYPE_ID','RELATED_TYPE'],
				[[$res->[1],$resr->[0],$resh->[0],'Manual']]);
			($rv)= $dbh->replace('RELATED',['FK_OBJECT_ID','FK_RELATED_ID','FK_CONTENTTYPE_ID','RELATED_TYPE'],
				[[$resr->[0],$res->[1],$viewtopic_type,'Manual']]);
		}
	}
	$sthr->finish;

}
$sth->finish;

#now update viewforums
my $s= WiganRL::Search->new; $s->table('VIEWFORUM');
for (@{$s->search}) {
	for ($cgi->param) {	$cgi->delete($_); }
	$_->update;
}